"""
公共方法
"""
import logging
import string
import random
import time
import traceback

from flask import Blueprint, make_response, current_app
from ronglian_sms_sdk import SmsSDK
import qiniu.config
from qiniu import Auth, put_file, etag

from common.models.user import UserBase
from common.utils.captcha import Captcha
from common.models import cache
from celery_task.main import celery_app
import requests
from common.models import rds, db, cache

# 容联
accId = '8aaf07087f77bf96017fd54021082f71'
accToken = 'fcc9d94e2c324d32a93081fe8323c959'
appId = '8aaf07087f77bf96017fd54021ff2f78'

# 七牛
# 需要填写你的 Access Key 和 Secret Key
access_key = 'ZxuCr1dxnenWx0-gGIBZcxOMcjytXtZISwgix36L'
secret_key = 'SJl9JmW7zB0j1xHlDPmyjTwJf5E7ksoQicqIDQT8'


def generate_code():
    return Captcha.gene_graph_captcha()


@celery_app.task(name='common.utils.utils.phone_code')
def phone_code(mobile, code):
    """
    短信验证码功能
    :return:
    """
    print('11111', mobile, code)
    logging.info('6666666666666666666666666666666666')
    # sdk = SmsSDK(accId, accToken, appId)
    # datas = (code, '5')
    resp = 1
    time.sleep(10)
    # resp = sdk.sendMessage('1', mobile, datas)
    return resp


def upload():
    # 构建鉴权对象
    q = Auth(access_key, secret_key)
    # 要上传的空间
    bucket_name = 'wangyufei911'
    # 上传后保存的文件名
    key = 'test/aaa.py'
    # 生成上传 Token，可以指定过期时间等
    token = q.upload_token(bucket_name, key, 3600)
    # 要上传文件的本地路径
    localfile = './main.py'
    ret, info = put_file(token, key, localfile)
    print(info)
    print(ret)
    assert ret['key'] == key
    assert ret['hash'] == etag(localfile)


def download():
    """

    """
    q = Auth(access_key, secret_key)
    base_url = 'http://%s/%s' % ('wangyufei911', 'test/aaa.py')
    private_url = q.private_download_url(base_url, expires=3600)
    print(private_url)
    r = requests.get(private_url)
    assert r.status_code == 200


def get_upload_token():
    """
    获取上传文件的token
    :return:
    """
    q = Auth(access_key, secret_key)
    # 要上传的空间
    bucket_name = 'courses1'
    # 上传后保存的文件名
    # 生成上传 Token，可以指定过期时间等
    token = q.upload_token(bucket_name, 3600)
    return token


def check_is_manager(user_id):
    """
    检查用户是否为管理员
    :return:
    """
    user = UserBase.query.get(user_id)
    # 判断该用户有没有添加的权限
    if user.is_superuser == 0:
        return False
    return True
